package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.entity.Wallet;
import com.example.demo.entity.WalletRecord;
import com.example.demo.mapper.WalletRecordMapper;
import com.example.demo.service.WalletService;
import com.example.demo.mapper.WalletMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author 三石
* @description 针对表【wallet】的数据库操作Service实现
* @createDate 2024-06-13 09:00:04
*/
@Service
public class WalletServiceImpl extends ServiceImpl<WalletMapper, Wallet>
    implements WalletService{

    @Resource
    public WalletMapper walletMapper;
    @Resource
    public WalletRecordMapper walletRecordMapper;

    @Override
    public Wallet SelectWalletByUid(Long userId) {
        return walletMapper.selectByUserId(userId);

    }

    @Override
    public List<WalletRecord> SelectWalletRecordByUid(Long userId) {

        Map<String,Object> columnMap = new HashMap<>();
        columnMap.put("user_id",userId);
        return walletRecordMapper.selectByMap(columnMap);
    }

    @Override
    public void addMoney(Long userId, Double money1) {
        Wallet wallet = walletMapper.selectByUserId(userId);
        UpdateWrapper<Wallet> wrapper = new UpdateWrapper<>();
        wrapper.eq("user_id", userId);
        wrapper.set("total_money", money(wallet.getTotalMoney()+money1));
        walletMapper.update(wrapper);

        //同时添加交易记录
        String orderNumber = String.valueOf(System.currentTimeMillis());
        LocalDateTime dateTime = LocalDateTime.now();

        WalletRecord walletRecord=new WalletRecord();
        walletRecord.setOrderNum(orderNumber);
        walletRecord.setCreateTime(dateTime);
        walletRecord.setUpdateTime(dateTime);
        wallet.setUserId(userId);
        walletRecord.setTotalMoney( money(wallet.getTotalMoney()+money1));
        walletRecord.setMoney(money1);
        walletRecord.setUserId(userId);
        walletRecord.setType("充值");
        walletRecordMapper.insert(walletRecord);
    }

    @Override
    public Wallet createWalletByUid(Long userId) {
        Wallet wallet=new Wallet();
        wallet.setTotalMoney(0.0);
        wallet.setUserId(userId);

        LocalDateTime dateTime = LocalDateTime.now();
        wallet.setCreateTime(dateTime);
        wallet.setUpdateTime(dateTime);
        walletMapper.insert(wallet);

        return null;
    }

    /**
     * 设置只保留两位小数
     * @param totalMoney
     * @return
     */
    public double money(double totalMoney){

        DecimalFormat df = new DecimalFormat("#.##");
        return Double.parseDouble(df.format(totalMoney));
    }
}




